package com.leetcode.partition2;

import com.leetcode.common.TreeNode;

/**
 * @author `RKC`
 * @date 2021/8/17 10:46
 */
public class LC110平衡二叉树 {

    public boolean isBalanced(TreeNode root) {
        return recursion(root) != -1;
    }

    //计算平衡二叉树的高度，如果不是平衡的二叉树，则返回-1
    private int recursion(TreeNode root) {
        if (root == null) return 0;
        int leftHeight = recursion(root.left);
        if (leftHeight == -1) return -1;
        int rightHeight = recursion(root.right);
        if (rightHeight == -1) return -1;
        //如果两颗子树的高度差大于1，也不是完全二叉树
        return Math.abs(leftHeight - rightHeight) > 1 ? -1 : 1 + Math.max(leftHeight, rightHeight);
    }
}
